package com.java.service.impl;

import com.java.entity.PageBean;
import com.java.entity.PsUser;
import com.java.mapper.PsUserMapper;
import com.java.redis.RedisLogin;
import com.java.service.PsUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

/**
 * @author caiyuan
 * @version 1.0
 * @Date 2020/6/11 14:48 Dream-Seeker
 * @Description
 */
@Service
public class PsUserServiceImpl implements PsUserService {
    @Autowired
    private PsUserMapper psUserMapper;
    @Autowired
    private RedisLogin redisLogin;

    @Override
    public PsUser login(String userName, String userpassword) {
        //获取redis缓存里寻找用户
        List<PsUser> psUserList = redisLogin.getAllUser();
        if (psUserList==null) {
            //未登录过用户
            //获取所有用户添加到缓存里
            redisLogin.setAllUser(psUserMapper.getAllUser());
            //获取登录对象【数据库查询】
            PsUser psUser = psUserMapper.login(userName, userpassword);
            if (psUser != null) {
                //用户不为空返回
                return psUser;
            }
        } else {
            for (PsUser psUser : psUserList) {
                if (psUser.getUserName().equals(userName) && psUser.getUserPassword().equals(userpassword)) {
                    return psUser;
                }
            }
        }
        return null;
    }

    @Override
    public PsUser getUserbyName(String userName) {
        return psUserMapper.getUserbyName(userName);
    }

    @Override
    public PageBean<PsUser> findByPage(int currentPage) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        PageBean<PsUser> pageBean = new PageBean<PsUser>();

        //每页显示的数据
        int pageSize = 5;
        pageBean.setPageSize(pageSize);

        //封装总记录数
        int totalCount = psUserMapper.selectCount();
        pageBean.setTotalCount(totalCount);

        //封装总页数
        double tc = totalCount;
        Double num = Math.ceil(tc / pageSize);//向上取整
        pageBean.setTotalPage(num.intValue());

        if (currentPage > pageBean.getTotalPage()) {
            //封装当前页数
            pageBean.setCurrPage(pageBean.getTotalPage());
        } else if (currentPage < 0) {
            pageBean.setCurrPage(1);
        } else {
            pageBean.setCurrPage(currentPage);
        }

        map.put("start", (currentPage - 1) * pageSize);
        map.put("size", pageBean.getPageSize());
        //封装每页显示的数据
        List<PsUser> list = psUserMapper.findByPage(map);
        pageBean.setLists(list);

        return pageBean;
    }

    @Override
    public Integer setLoginTime(PsUser user) {
        return psUserMapper.setLoginTime(user);
    }
}
































